package com.health.httpbean.upload;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

import com.google.gson.GsonBuilder;
import com.health.httpbean.HttpConstant;
import com.health.tablebean.JTYS_SignPictureData;
import com.health.tools.FileHelper;
import com.health.tools.JX_UploadData;
import com.health.tools.ModuleName;
import com.health.tools.UploadDataBean;
import com.health.tools.WebService;
import com.health.viewscontrols.MainActivity_Menu_Tj;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.settings.Manager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import rxhttp.RxHttp;

/**
 * WebService数据上传类
 */
public class ArchiveUploadDatas {
    private final static int INIT = -1;
    private Context context;
    private int dataCount = INIT;
    private UploadDataBean[] dataBeans;
    private  int j = 0;
    private  int k = 0;
    int s=0;
    int f=0;
    int count;

    /**
     * 数据上传类
     *
     * @param context   Activity
     * @param dataBeans
     */
    public ArchiveUploadDatas(Context context, UploadDataBean... dataBeans) {
        this.context = context;
        this.dataBeans = dataBeans;
        dataCount = INIT;
    }

    /**
     * 数据上传类
     *
     * @param context   Activity
     * @param dataBeans
     */
    public ArchiveUploadDatas(Context context, List<UploadDataBean> dataBeans) {
        this.context = context;
        MainActivity_Menu_Tj cs=(MainActivity_Menu_Tj)context;
        cs.getHandler();
        if (dataBeans != null) {
            int size = dataBeans.size();
            this.dataBeans = new UploadDataBean[size];
            this.dataBeans = dataBeans.toArray(this.dataBeans);
        }

        dataCount = INIT;
    }

    /**
     * 开始上传数据
     *
     * @author 鹿云龙
     * @date 2017年12月18日 下午1:48:38
     */
    public void uploadDatas() {
        dataCount = INIT;
        log("开始上传数据");
        if (dataBeans != null && dataBeans.length > 0) {
            uploadData();
        } else {
            log("+++++++++++++++++");
            setDialogText("暂无数据上传！");
        }
    }
    /**
     * 随访表上传完 之后调用一次
     */
    private void sendFollowTable() {
//        String doctorId = SPUtils.getInstance().getString(HttpConstant._DOCTOR_ID,"");
        Log.e("当前医生", NovaApplication.getJgrno());
        RxHttp.postForm(HttpConstant.sendFollowTable + NovaApplication.getJgrno())
                .asString()
                .subscribe(resultBean -> {
                    Log.e("xiaoxin", "sendFollowTable: 11" );
                }, throwable -> {
                    Log.e("xiaoxin", "sendFollowTable:22 " );
                });
    }
    // 递归调用上传所有数据
    private void uploadData() {
        if (dataCount != INIT) {
            wait(2000);
        }
        dataCount += 1;
        Log.e("eeeeeeeeeeeeee", dataBeans.length+"");
        if (dataCount == dataBeans.length) {
            log("上传结束");
            dataCount = INIT;
            setDialogText("数据上传完成！");
//            sendFollowTable();
            return;
        }
        final UploadDataBean data = dataBeans[dataCount];
        wait(1000);

        if (dataCount < dataBeans.length) {

            //上传照片
            if (ModuleName.UPLOAD_PHOTO.equals(data.getDataName())) {
                try {
                    final List<Object> datas = data.getDatas();
                    count=datas.size();
                    if (datas!= null && datas.size()>0) {
                        for (int i = 0; i < datas.size(); i++) {
                            JTYS_SignPictureData picture = (JTYS_SignPictureData) datas.get(i);
                            String fileURL = picture.getPhotoPath();
                            String fileName = picture.getPhotoName();
                            String cardNum = picture.getCardNum();
                            String type = picture.getRes0();
                            String uuid = picture.getRes1();
                            Log.e("upPhoto--",picture.toString());
                            new WebService(context) {
                                @Override
                                public void complete(final String message) {
                                    try {
                                        JSONObject obj = new JSONObject(message);
                                        String state = obj.getString("state");
                                        String cardid="";
                                        String personalid="";
                                        if(obj.has("cardid")){
                                            cardid=obj.getString("cardid");
                                        }
                                        if(obj.has("personalid")){
                                            personalid=obj.getString("personalid");
                                        }


                                        if (state.equals("000")) {
                                            List<JTYS_SignPictureData> pictureDatas = NovaApplication.fdbmanger
                                                    .findAllByWhere(JTYS_SignPictureData.class, "photoName ='" + obj.getString("fileName") + "'");
                                            if (pictureDatas.size() > 0) {
                                                JTYS_SignPictureData pictureData = pictureDatas.get(0);
                                                pictureData.setIsUpdate("N");
                                                NovaApplication.fdbmanger.updata(pictureData, "photoName ='" + obj.getString("fileName") + "'");
                                                j++;
                                                if (j + k == datas.size()) {
                                                    Message ms = new Message();
                                                    Bundle bundle = new Bundle();
                                                    bundle.putString("count", j + "/" + k + "/" + data.getDataName());
                                                    bundle.putString("uploadSuccess", "true");
                                                    ms.setData(bundle);//bundle传值，耗时，效率低
                                                    ms.what = 11;
                                                    Manager.getInstance().sendCountMessage(ms);
                                                }
                                            }
                                        } else if(state.equals("003")){
                                            List<JTYS_SignPictureData> pictureDatas = NovaApplication.fdbmanger
                                                    .findAllByWhere(JTYS_SignPictureData.class, "photoName ='" + obj.getString("fileName") + "'");
                                            if (pictureDatas.size() > 0) {
                                                JTYS_SignPictureData pictureData = pictureDatas.get(0);
                                                pictureData.setIsUpdate("N");
                                                NovaApplication.fdbmanger.updata(pictureData, "photoName ='" + obj.getString("fileName") + "'");
                                                j++;
                                                if (j + k == datas.size()) {
                                                    Message ms = new Message();
                                                    Bundle bundle = new Bundle();
                                                    bundle.putString("count", j + "/" + k + "/" + data.getDataName());
                                                    bundle.putString("uploadSuccess", "true");
                                                    ms.setData(bundle);//bundle传值，耗时，效率低
                                                    ms.what = 11;
                                                    Manager.getInstance().sendCountMessage(ms);
                                                }
                                            }
                                        } else {
                                            FileHelper.addTxtToFileWrite(message);
                                            if("001".equals(state)){
                                                FileHelper.addTxtToFileWrite("表名：JTYS_SignPictureData;"+"CardNum:"+cardid+",personalid:"+personalid+";错误原因:无此人档案信息");
                                            }else  if("002".equals(state)){
                                                FileHelper.addTxtToFileWrite("表名：JTYS_SignPictureData;"+"CardNum:"+cardid+",personalid:"+personalid+";错误原因:无签约表");
                                            }else if("004".equals(state)){
                                                FileHelper.addTxtToFileWrite("表名：JTYS_SignPictureData;"+"CardNum:"+cardid+",personalid:"+personalid+";错误原因:更新签约表失败");
                                            }else if("005".equals(state)){
                                                FileHelper.addTxtToFileWrite("表名：JTYS_SignPictureData;"+"CardNum:"+cardid+",personalid:"+personalid+";错误原因:必填项未填");
                                            }else if("006".equals(state)){
                                                FileHelper.addTxtToFileWrite("表名：JTYS_SignPictureData;"+"CardNum:"+cardid+",personalid:"+personalid+";错误原因:文件类型不合法");
                                            }else if("007".equals(state)){
                                                Log.e("TAG","报007错误了");
                                                FileHelper.addTxtToFileWrite("表名：JTYS_SignPictureData;"+"CardNum:"+cardid+",personalid:"+personalid+";错误原因:文件名为空或包含非法字符");
                                            }

                                            k++;
                                            if (j + k == datas.size()) {
                                                Message ms = new Message();
                                                Bundle bundle = new Bundle();
                                                bundle.putString("count", j + "/" + k + "/" + data.getDataName());
                                                bundle.putString("uploadSuccess", "false");
                                                ms.setData(bundle);//bundle传值，耗时，效率低
                                                ms.what = 11;
                                                Manager.getInstance().sendCountMessage(ms);
                                            }
                                        }
                                    } catch (JSONException e) {
                                        k++;
                                        FileHelper.addTxtToFileWrite(e.toString());

                                        if (j + k == datas.size()) {
                                            Message ms = new Message();
                                            Bundle bundle = new Bundle();
                                            bundle.putString("count", j + "/" + k + "/" + data.getDataName());
                                            bundle.putString("uploadSuccess", "false");
                                            ms.setData(bundle);//bundle传值，耗时，效率低
                                            ms.what = 11;
                                            Manager.getInstance().sendCountMessage(ms);
                                        }
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onError(String message) {
                                    k++;
                                    FileHelper.addTxtToFileWrite(message);
                                    if (j + k == datas.size()) {
                                        Message ms = new Message();
                                        Bundle bundle = new Bundle();
                                        bundle.putString("count", j + "/" + k + "/" + data.getDataName());
                                        bundle.putString("uploadSuccess", "false");
                                        ms.setData(bundle);//bundle传值，耗时，效率低
                                        ms.what = 11;
                                        Manager.getInstance().sendCountMessage(ms);
                                    }
                                }
                            }.uploadFile(data.getMethod(), fileURL, fileName, data.getModule(), cardNum, type, uuid);
                        }
                    }
                } catch (Exception e) {
                    k++;
                    FileHelper.addTxtToFileWrite(e.toString());
                    if (j + k == count) {
                        Message ms = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("count", j + "/" + k + "/" + data.getDataName());
                        bundle.putString("uploadSuccess", "false");
                        ms.setData(bundle);//bundle传值，耗时，效率低
                        ms.what = 11;
                        Manager.getInstance().sendCountMessage(ms);
                    }
                    Log.e("*******************",data.getDataName() + "数据上传失败!");
                    e.printStackTrace();
                    setDialogText(data.getDataName() + "数据上传失败!");
                }
            } else {
                try {
                    String ss=data.getDataJsonName();
                    final List<Object> datas = data.getDatas();
                    HashMap<String, Object> uploadParams = new HashMap<String, Object>();
                    uploadParams.put(data.getDataJsonName(), new GsonBuilder().create().toJson(data.getDatas()));

                    Log.e("转换数据：", ss+"***********"+new GsonBuilder().create().toJson(data.getDatas()).toString());
//                    FileHelper.addTxtToFileWrite(new GsonBuilder().create().toJson(data.getDatas()).toString());
                    new WebService(context) {
                        @Override
                        public void complete(final String message) {
                            Log.e("上传返回数据：",  message);

                            if (!("[]".equals(message))) {
                                final int[] jx_data = JX_UploadData.jx_data(message, data.getDataType());
                                s=jx_data[0];
                                f=jx_data[1];
                                Message ms=new Message();
                                Bundle bundle=new Bundle();
                                bundle.putString("count", s+"/"+f+"/"+data.getDataName());
                                bundle.putString("uploadSuccess","true");
                                ms.setData(bundle);//bundle传值，耗时，效率低
                                ms.what=11;
                                Manager.getInstance().sendCountMessage(ms);
                                Log.e("上传返回数据：" ,"11111111111111111");
                            }
                        }
                        @Override
                        public void onError(String message) {
//                            setDialogText(data.getDataName() + "数据上传失败!");
                            FileHelper.addTxtToFileWrite(message);
                            final int[] jx_data = JX_UploadData.jx_data(message, data.getDataType());
                            s=jx_data[0];
                            f=jx_data[1];
                            Message ms=new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("count", s+"/"+f+"/"+data.getDataName());
                            bundle.putString("uploadSuccess","false");
                            ms.setData(bundle);//bundle传值，耗时，效率低
                            ms.what=11;
                            Manager.getInstance().sendCountMessage(ms);
                            Log.e("上传返回数据：" ,"11111111111111111");
                            uploadData();
                        }
                    }.uploaddata(data.getMethod(), uploadParams, data.getModule());
                } catch (Exception e) {
                    e.printStackTrace();
                    FileHelper.addTxtToFileWrite(e.toString());

                    setDialogText(data.getDataName() + "数据上传失败!");
                    uploadData();
                }
            }
        }
    }

    private void setDialogText(final String str) {
        ((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                resultDialog.setText(str);
            }
        });
    }

    private void wait(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }

    private void log(String msg) {
        Log.i("tag", "[UploadDatas]" + msg);
    }

}